import { ref,onMounted } from 'vue';
import ImageCache from './setting-components/ImageCache';
import ImageRepository from './setting-components/ImageRepository';
import axios from 'axios';
import { useRoute, useRouter } from 'vue-router'
import { ElMessageBox,ElMessage } from 'element-plus'

export default {
    setup(){
        const appData = ref({
            cache_registry: {},
            cache_rules: [],
            registry_sources: [],
        });

        const open = ref(false);
        const tabsActive = ref('1');
        const refCache = ref(null);
        const refRepository = ref(null);

        const group = useRoute().query.group?.replace(/\/$/,'');
        const ingress_name = useRoute().query.ingress_name;

        const ingressData = ref({});
        const imageCacheApp = ref({});

        const getData = ()=>{
            if(!group){return}
            axios.post('/api/setting/get',{
                group: group
            }).then(res=>{
                let data = res?.data?.data || {};
                appData.value = data;
            })
            
            let paneltoken = window.$wujie?.props?.paneltoken;
            if(ingress_name){
                axios.get('/apis/networking.k8s.io/v1/namespaces/default/ingresses/' + ingress_name,{
                    baseURL: '',
                    customToken: paneltoken,
                }).then(res=>{
                    open.value = res?.data?.metadata?.annotations?.['w7.cc/registrycache'] === 'true';
                    ingressData.value = res?.data;
                }).catch(()=>{})
            }
        }

        const submit = ()=>{
            let o = {
                group: group,
                cache_storage_registry: {
                    ...refRepository.value.form,
                    server_url: refRepository.value.form?.server_url_pre + refRepository.value.form?.server_url_after,
                },
                repository_cache_rules: refCache.value.form.cache_rules,
                registry_sources: refCache.value.form.registry_sources?.map(i=>{
                    return {
                        ...i,
                        server_url: i.server_url_pre + i.server_url_after,
                    }
                }),
                extra: {
                    ingress_name: ingress_name,
                },
            }
            o.registry_sources.map(i=>{
                i.weight = Number(i.weight)
                if(i.proxy?.port){
                    i.proxy.port = Number(i.proxy.port)
                }
                if(!i.proxy?.server_url){
                    i.proxy = null;
                }
            })
            o.repository_cache_rules.map(i=>{
                i.repository_name = i.repository_name?.map(rn=>rn.replace(/^\//,''));
                i.weight = Number(i.weight);
                i.cache_ttl = Number(i.cache_ttl) || 0;
            })
            
            axios.post('/api/setting/set',o).then(res=>{
                editIngress();
            }).then(res=>{
                window.$wujie?.bus.$emit('submit',{
                    from:'image-cache',
                    open: open.value,
                })
                console.log('emit submit')
                ElMessage.success('操作成功');
            })
        }

        
        const editIngress = async ()=>{
            let paneltoken = window.$wujie?.props?.paneltoken;
            if(!ingress_name){return}

            
            await axios.get('/apis/networking.k8s.io/v1/namespaces/default/ingresses/' + ingress_name,{
                baseURL: '',
                customToken: paneltoken,
            }).then(res=>{
                ingressData.value = res?.data;
            }).catch(()=>{})
            
            await axios.get('/apis/microapp.w7.cc/v1alpha1/namespaces/default/microapps?labelSelector=w7.cc/identifie=w7-registrycache',{
                baseURL: '',
                customToken: paneltoken,
            }).then(res=>{
                if(!res?.data){return Promise.reject();}
                imageCacheApp.value = res?.data?.items?.[0];
            }).catch(()=>{})

            let operations = [];
            let ann = ingressData.value.metadata?.annotations;
            if(!open.value){
                if(ann['w7.cc/origin-config']){
                    operations.push({
                        op: 'replace',
                        path: '/spec/rules/0/http/paths/0/backend',
                        value: JSON.parse(ann['w7.cc/origin-config'])
                    })
                    operations.push({
                        op: 'remove',
                        path: '/metadata/annotations/w7.cc~1origin-config',
                    })
                }
                
                if(ann['w7.cc/rewrite-config']){
                    let json = JSON.parse(ann['w7.cc/rewrite-config'])

                    operations.push({
                        op: 'remove',
                        path: '/metadata/annotations/w7.cc~1rewrite-config',
                    })
                    operations.push({
                        op: 'replace',
                        path: '/metadata/annotations/higress.io~1enable-rewrite',
                        value: json?.['higress.io/enable-rewrite'] || 'false',
                    })
                    operations.push({
                        op: 'replace',
                        path: '/metadata/annotations/higress.io~1rewrite-target',
                        value: json?.['higress.io/rewrite-target'] || '',
                    })
                    operations.push({
                        op: 'replace',
                        path: '/metadata/annotations/higress.io~1upstream-vhost',
                        value: json?.['higress.io/upstream-vhost'] || '',
                    })
                }
                operations.push({
                    op: 'replace',
                    path: '/metadata/annotations/w7.cc~1registrycache',
                    value: 'false',
                })
            }else{
                if(!ann['w7.cc/origin-config']){
                    operations.push({
                        op: 'replace',
                        path: '/metadata/annotations/w7.cc~1origin-config',
                        value: JSON.stringify(ingressData.value?.spec?.rules?.[0]?.http?.paths?.[0]?.backend),
                    })
                }
                
                if(ann['higress.io/enable-rewrite']=='true'){
                    operations.push({
                        op: 'replace',
                        path: '/metadata/annotations/w7.cc~1rewrite-config',
                        value: JSON.stringify({
                            'higress.io/enable-rewrite': ann['higress.io/enable-rewrite'],
                            'higress.io/rewrite-target': ann['higress.io/rewrite-target'],
                            'higress.io/upstream-vhost': ann['higress.io/upstream-vhost'],
                        })
                    })
                    operations.push({
                        op: 'replace',
                        path: '/metadata/annotations/higress.io~1enable-rewrite',
                        value: 'false',
                    })
                    operations.push({
                        op: 'replace',
                        path: '/metadata/annotations/higress.io~1rewrite-target',
                        value: '',
                    })
                    operations.push({
                        op: 'replace',
                        path: '/metadata/annotations/higress.io~1upstream-vhost',
                        value: '',
                    })
                }
                operations.push({
                    op: 'replace',
                    path: '/spec/rules/0/http/paths/0/backend',
                    value: {
                        service:{
                            name: imageCacheApp.value?.spec?.config?.props?.serviceName,
                            port:{
                                number: Number(imageCacheApp.value?.spec?.config?.props?.servicePort)
                            }
                        }
                    },
                })
                operations.push({
                    op: 'replace',
                    path: '/metadata/annotations/w7.cc~1registrycache',
                    value: 'true',
                })
            }

            await axios.patch('/apis/networking.k8s.io/v1/namespaces/default/ingresses/'+ ingress_name, operations, {
                baseURL: '',
                customToken: paneltoken,
                headers: {
                    'Content-Type': 'application/json-patch+json',
                },
            }).then(res=>{}).catch(()=>{})

        }

        onMounted(()=>{
            getData();
        })

        return ()=>(<div class="padding-20">
            <div className='df ai-c mb-10'>
                <span>开启：</span>
                <el-switch
                    modelValue={open.value}
                    onUpdate:modelValue={e => {open.value = e;} }
                ></el-switch>
            </div>
            <el-tabs
                modelValue={tabsActive.value}
                onUpdate:modelValue={e => {tabsActive.value = e;} }
            >
                <el-tab-pane label="缓存镜像配置" name="1">
                    <ImageCache
                        ref={refCache}
                        data={appData.value}
                    ></ImageCache>
                </el-tab-pane>
                <el-tab-pane label="缓存镜像仓库配置" name="2">
                    <ImageRepository
                        ref={refRepository}
                        data={appData.value}
                    ></ImageRepository>
                </el-tab-pane>
            </el-tabs>

            <div className='mt-20'>
                <el-button type="primary" onClick={submit}>保存</el-button>
            </div>
        </div>)
    }
}